class TicketSyncForm
{
    constructor(config)
    {
        this.userList = [];
        this.exceptList = [];
        this.formSchema = {};
        this.syncTickets = new SyncTickets(config);
        this.Init();
    }

    Init()
    {
        // add css
        jQuery('head').append('<style>.ui-widget.ui-widget-content {z-index:3400;}#sync-issue-form-container span.help-block{color:orangered;}</style>');
        jQuery('head').append('<link rel="stylesheet" href="//code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">');
        this.initButton();
    }

    initButton()
    {
        let self = this;
        let layout = `
        <li id="sync-tickets-li" style="padding: 5px;"><button id="sync-submit">Sync</button></li>
`;
        jQuery('.aui-header-primary ul.aui-nav').append(layout);

        jQuery('#sync-submit').on('click', function() {
            jQuery('#sync-loading').remove();
            self.renderPopup();
        });
    }

    renderPopup()
    {
        let self = this;

        let layout = `
        <section id="sync-issue-dialog" class="aui-dialog2 aui-layer jira-dialog2 jira-dialog-core aui-dialog2-large jira-dialog-open jira-dialog-content-ready" role="dialog" aria-labelledby="jira-dialog2__heading" style="z-index: 3000;" data-aui-focus="false" data-aui-blanketed="true" open="" tabindex="-1">
        <header class="aui-dialog2-header jira-dialog-core-heading">
        <h2 id="jira-dialog2__heading" title="Record Time">{{title}}</h2>
        </header>
        <div class="aui-dialog2-content jira-dialog-core-content">
        <div class="qf-container">
        <div class="form-footer">
        <div class="dialog-error">
        <div id="sync-issue-form-container"><form class="aui"></form></div>
        </div>
        </div>
        </div>
        </div>
        <footer class="aui-dialog2-footer">
        <div class="buttons-container form-footer">
        <div class="buttons">
        <span class="throbber"></span>
        <button class="button aui-button aui-button-primary" id="sync-ticket-status">Save</button>&nbsp;
        <button class="aui-button aui-button-link cancel" id="aui-dialog-close" resolved="">Close</button>
        </div></div></footer></section>
        <div id="jira-bg-mark" aria-hidden="true" class="aui-blanket" tabindex="0" style="z-index: 2980;"></div>
        `;
        layout = layout.replace('{{title}}', jQuery('#summary-val').text());

        jQuery('#sync-issue-dialog-sync').remove();
        jQuery('body').append(layout);
        jQuery('#jira-bg-mark').on('click', (e) => {
            jQuery('#sync-issue-dialog').remove();
            jQuery('#jira-bg-mark').remove();
        });
        jQuery('#aui-dialog-close').on('click', (e) => {
            jQuery('#sync-issue-dialog').remove();
            jQuery('#jira-bg-mark').remove();
        });

        self.initForm();
    }

    initForm()
    {
        let self = this;
        let options = self.formSchema;

        // onSubmit
        options.onSubmit = async function (errors, values) {
            let issueKeyOrId = jQuery('#key-val').data('issue-key');
            let keys = Object.keys(values.fields);
            keys.forEach((key) => {
                console.log('#item', '[name="fields.' + key + '"]');
                if (jQuery('[name="fields.' + key + '"]').attr('multiple')=='multiple') {
                    let _values = [];
                    jQuery('[name="fields.' + key + '"] option:selected').each((idx, ele) => {
                        _values.push({"value":jQuery(ele).val()});
                    });
                    if (values.hasOwnProperty('fields') && values.fields.hasOwnProperty(key)) {
                        values.fields[key] = _values;
                    }
                }
            });
             console.log('### form values before:', values);
            values.fields.customfield_13700 = [values.fields.customfield_13700];

            // validate and submit
            console.log('### form values', values);
            try {
                // delete developer, ticket_action, 
                let _values = values;
                let comment = _values.fields.comment;

                if (!self.exceptList.includes(values.fields.developer)) {
                    delete _values.fields.customfield_13431; // delete ticket_action
                }

                delete _values.fields.comment; // delete comment
                delete _values.fields.customfield_13408; // delete timetracking
                delete _values.fields.developer; // delete developer

                // update to origin JIRA
                await self.updateOriginIssue(issueKeyOrId, _values);
                // sync to target JIRA
                let childTicket = await self.syncTargetTickets(issueKeyOrId);
                let data = {
                    ticket: childTicket,
                    parentTicketId: issueKeyOrId,
                    newValues: values
                };

                self.afterSubmit(data);

                if (comment) {
                    await self.addComment(childTicket.key, comment + ' [~' + childTicket.fields.assignee.name + ']').then((resp) => {
                        jQuery('#aui-dialog-close').trigger('click');
                        jQuery('#sync-sc-developer').trigger('click');
                    });
                } else {
                    jQuery('#aui-dialog-close').trigger('click');
                    jQuery('#sync-sc-developer').trigger('click');
                }

                if (childTicket.id) {
                    // update resources cache
                    let fixVersion = childTicket.fields.fixVersions.pop();
                    let cacheKey = 'resources-data-' + fixVersion.name.split('.').join('_');
                    localStorage.setItem(cacheKey, '');
                }

                //
                //jQuery('#aui-dialog-close').trigger('click');
            } catch(e) {
                console.error('Sync Detail Error:', e);
            }

            return false;
        }

        // init from
        jQuery('#sync-issue-form-container form').jsonForm(options);

        // add autocomplete
        jQuery('.jsonform-error-fields---developer input.form-control').autocomplete({
            source: self.userList
        });

        jQuery('#sync-ticket-status').on('click', function() {
            // submit form
            // remove loadingDiv
            jQuery('#sync-loading').remove();
            if ('[object Undefined]' != Object.prototype.toString.call(loadingDiv)) {
                jQuery('#sync-ticket-status').after(loadingDiv);
            }
            jQuery('#sync-issue-form-container form').trigger('submit');
        });
    }

    afterSubmit(childTicket)
    {
        // do something after submit
    }

    async updateOriginIssue(issueKeyOrId, values)
    {
        return await this.syncTickets.sourceJira.updateIssue(issueKeyOrId, values);
    }

    async syncTargetTickets(issueKeyOrId)
    {
        return await this.syncTickets.sync(issueKeyOrId);
    }

    async addComment(issueKeyOrId, comment)
    {
        return await this.syncTickets.targetJira.addComment(issueKeyOrId, comment);
    }
}
